__author__ = 'JackSong'
import sys
import os.path
import tornado.ioloop
import tornado.web
import tornado.httpserver
import tornado.options
import logging
from tornado.options import options
from sqlalchemy.orm import scoped_session, sessionmaker
from config import init_config
from urls import handlers
from ioloop import IOloop
from utils.tools import check_python_version_is_2
from utils.data import get_engine
from tornado.queues import Queue
from utils.redis import get_redis_client
queues = Queue(maxsize=10)

if sys.version_info.major == 2:
    reload(sys)
    sys.setdefaultencoding('utf-8')
else:
    import tornado.platform.asyncio
    import asyncio

settings = dict(
    template_path=os.path.join(os.path.dirname(__file__), "templates"),
    static_path=os.path.join(os.path.dirname(__file__), "templates/dist/static"),
)


class Application(tornado.web.Application):
    def __init__(self):
        engine = get_engine()
        tornado.web.Application.__init__(self, handlers, **settings)
        self.session = scoped_session(sessionmaker(bind=engine), self.get_id)
        self.queues = queues
        self.redis = get_redis_client()
        self.access_log = logging.getLogger("tornado.access")
        streamhandler = logging.StreamHandler()
        self.access_log.removeHandler(streamhandler)

    def get_id(self):
        return id(self)


async def write_file_queues():
    async for item in queues:
        try:
            item()
        finally:
            queues.task_done()


def main():
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    print('Server Starting port on %s' % (options.port,))
    instance = IOloop.instance(queues).ioloop
    instance.run_sync(write_file_queues)
    instance.start()


def migrate_database():
    from model import Base
    engine = get_engine()
    Base.metadata.create_all(engine)


if __name__ == "__main__":
    import sys
    init_config()
    if not check_python_version_is_2():
        asyncio.set_event_loop(asyncio.new_event_loop())
    options.parse_config_file("openssh.conf")
    options.parse_command_line()
    command_len = len(sys.argv)
    if command_len == 1:
        main()
    else:
        {"migrate": migrate_database}[sys.argv[1]]()
